import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  withCredentials: true, // 允许携带 cookie
  crossDomain: true, // 允许跨域
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 添加token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    
    // 处理跨域请求
    if (config.url.includes('douyin.com')) {
      // 对抖音的请求特殊处理
      config.headers = {
        ...config.headers,
        'Referer': 'https://www.douyin.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
      }
    }
    
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    // 根据 success 判断请求是否成功
    if (res.code === '200') {  // success为0表示成功
      return res.data
    } else {
      // 处理业务错误
      const errorMessage = res.message || '请求失败'
      ElMessage({
        message: errorMessage,
        type: 'error',
        duration: 3000
      })

      // 处理特定错误码
      switch (res.code) {
        case '401':
          // 未授权，清除token并跳转到登录页
          localStorage.removeItem('token')
          window.location.href = '/login'
          break
        case '403':
          // 权限不足
          ElMessage({
            message: '权限不足',
            type: 'error',
            duration: 3000
          })
          break
        case '500':
          // 服务器错误
          ElMessage({
            message: '服务器错误',
            type: 'error',
            duration: 3000
          })
          break
        // 可以添加其他错误码的处理
      }

      return Promise.reject(new Error(errorMessage))
    }
  },
  error => {
    // 处理 HTTP 错误
    console.error('Response error:', error)
    let message = '网络错误'
    
    if (error.response) {
      switch (error.response.status) {
        case 400:
          message = '请求错误'
          break
        case 401:
          message = '未授权，请登录'
          // 清除token并跳转到登录页
          localStorage.removeItem('token')
          window.location.href = '/login'
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求地址出错'
          break
        case 408:
          message = '请求超时'
          break
        case 500:
          message = '服务器内部错误'
          break
        case 501:
          message = '服务未实现'
          break
        case 502:
          message = '网关错误'
          break
        case 503:
          message = '服务不可用'
          break
        case 504:
          message = '网关超时'
          break
        case 505:
          message = 'HTTP版本不受支持'
          break
        default:
          message = `连接错误${error.response.status}`
      }
    }

    ElMessage({
      message: error.response?.data?.message || message,
      type: 'error',
      duration: 3000
    })
    
    return Promise.reject(error)
  }
)

// 封装请求方法
export const request = {
  get(url, params, config = {}) {
    return service.get(url, { params, ...config })
  },

  post(url, data, config = {}) {
    return service.post(url, data, config)
  },

  put(url, data, config = {}) {
    return service.put(url, data, config)
  },

  delete(url, params, config = {}) {
    return service.delete(url, { params, ...config })
  },

  // 上传文件
  upload(url, file, config = {}) {
    const formData = new FormData()
    formData.append('file', file)
    return service.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      ...config
    })
  },

  // 下载文件
  download(url, params, config = {}) {
    return service.get(url, {
      params,
      responseType: 'blob',
      ...config
    })
  },

  // 添加跨域视频请求方法
  proxyVideo(url, config = {}) {
    return service.get('/douyin-proxy', {
      params: { url },
      ...config,
      headers: {
        ...config.headers,
        'Referer': 'https://www.douyin.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
      }
    })
  },

  // 添加跨域资源请求方法
  crossOrigin(url, config = {}) {
    return service.get(url, {
      ...config,
      proxy: {
        host: import.meta.env.VITE_PROXY_HOST,
        port: import.meta.env.VITE_PROXY_PORT
      }
    })
  }
}

export default service 